//Module definition
var SRP = SRP || (function () {
    return {};
}());

//PACKAGE.common = (function (PACKAGE,$) {
//
//    //$(document).ready(function() {
//        //exampleFunction("estoy de pruebas");
//    //});
//
//    function exampleFunction(text){
//        console.log(text);
//    }
//
//    return{
//        exampleFunction:exampleFunction
//    }
//
//}(PACKAGE||{},jQuery));

SRP.search = (function(SRP,$){

//the message to display in the ajax waiting page
        var waitingMessage = '<div><div style="clear:both;"><img alt="Loading" src="/ota/themes/' + i18n['common.siteid'] + '/img/loadingAjax.gif" style="display:block;margin-left: auto;margin-right: auto;"/></div><div style="clear:both"><h2><tc:getSitePresentationKey brandCode="' +  i18n['common.pleaseWait'] + '" key="common.pleaseWait"/></h2> <h2>' + i18n['common.updatingResults'] + '</h2></div></div>'

        $(window).on('beforeunload ',function() {
            //this is to avoid the holding page being displayed (and therefore blocking the customer) when hitting back button
        });

        var addToCompareTray=function(index,url,type){
            $.ajax ({
                type : "POST",
                url : type,
                data : url,
                success : function(data) {
                    $('#compareTray').html(dataFilter(data));
                    if(type=="/ota/addtriptocompare"){
                        if ($('#detailedViewLoaded').length > 0) {
                            $("#removeCompare"+index).css("display", "block");
                            $("#addCompare"+index).css("display", "none");
                        }
                        if ($('#imageViewLoaded').length > 0) {
                            $("#removeCompareImg"+index).css("display", "block");
                            $("#addCompareImg"+index).css("display", "none");
                        }
                        if ($('#imageMapLoaded').length > 0) {
                            $("#removeCompareMap"+index).css("display", "block");
                            $("#addCompareMap"+index).css("display", "none");
                            if($('#addCompareMapOriginal' + index).length > 0) {
                                $("#removeCompareMapOriginal"+index).css("display", "block");
                                $("#addCompareMapOriginal"+index).css("display", "none");
                            }
                        }
                    }else{
                        if ($('#detailedViewLoaded').length > 0) {
                            $("#removeCompare"+index).css("display", "none");
                            $("#addCompare"+index).css("display", "block");
                        }
                        if ($('#imageViewLoaded').length > 0) {
                            $("#removeCompareImg"+index).css("display", "none");
                            $("#addCompareImg"+index).css("display", "block");
                        }
                        if ($('#imageMapLoaded').length > 0) {
                            $("#removeCompareMap"+index).css("display", "none");
                            $("#addCompareMap"+index).css("display", "block");
                            if($('#addCompareMapOriginal' + index).length > 0) {
                                $("#removeCompareMapOriginal"+index).css("display", "none");
                                $("#addCompareMapOriginal"+index).css("display", "block");
                            }
                        }
                    }
                    // updating the shortlist in the tcheader
                    $('#viewCompareHeader').html($('#viewCompareHeaderHidden').html());
                }
            });
        }

        var changeInputHiddenOrderType=function(orderType){
            document.getElementById('orderType').value=orderType;           
        }

        var removeFromComparePage=function(url){
            $('#ter').block({ message: waitingMessage, css: {  } });
            $.ajax ({
                type : "POST",
                url : "/ota/removetriptocompare",
                data : url+"&comparePage=true",
                success : function(data) {
                    $('#ter').html(dataFilter(data));
                    $('#ter').unblock();
                    // updating the shortlist in the tcheader
                    $('#viewCompareHeader').html($('#viewCompareHeaderCompPageHidden').html());
                }
            });
        }

        var displayCompareTray=function(url){
            // don't want to display adverts on compare page
            $('.advt').html('');

            $('#'+"ct").block({ message: waitingMessage, css: {  } });
            $.ajax ({
                type : "POST",
                url : "/ota/displaytriptocompare",
                data : url,
                success : function(data) {
                    $('#ter').html(dataFilter(data));
                    document.getElementById("pri").style.display= "none"
                    document.getElementById("sec").style.display= "none"
                    $('#'+"ct").unblock();
                    document.getElementById("ter").style.display= "block"
                    document.getElementById("compareTray").style.display= "none"
                    element_to_scroll_to = document.getElementById('WarningCompareAnchor');
                    element_to_scroll_to.scrollIntoView();
                }
            });
        }

        var isPapi=function(){
            var a = $('input[id^="papiContext"]').size()
            if (a >0){
                return true;
            }else{
                return false;
            }
        }

        var sortAndPaginatePackages=function(packagesCurrentPage,maxResponses,from){        	
            if(isPapi()){
                //TODO findme eliminate this dependency is possible and pertinent
                PAPI.panel.calculatePapiPagination(packagesCurrentPage,maxResponses);
            }


            // need to hardcode top positioning as height too large
            $('#sec').block({ message: waitingMessage, centerY: 0,	css: { top: '105px'} });

            if(maxResponses==null){
                maxResponses = document.getElementById('SelectMaxResponses').options[document.getElementById('SelectMaxResponses').selectedIndex].value;
            }

            //we need to update the values in the form
            $('#maxResponses').val(maxResponses);
            $('#packagesCurrentPage').val(packagesCurrentPage);

            //this is to calculate the page that we have to search for just in case that the customer has change the number of results per page filter
            if($('#initialIndex').val()!=-1 && from =='numberResultsFilter'){
                page = $('#initialIndex').val() / maxResponses;
                $('#packagesCurrentPage').val(Math.floor(page));
            }
            searchCall();

        }
        var searchAsyncCall=function(){
            $('#sec').block({ message: waitingMessage, centerY: 0,	css: { top: '105px'} });
            searchCall();
        }
        var searchCall=function(){    	
            if(isPapi()){            	
                $.ajax ({
                    type : "POST",
                    url : "/ota/" + $('#tabName').val() + "asyncsearchresult",
                    data : $('#searchPanelFormId').find('input, select').not('[value=""], [value="-1"]').serialize(),
                    error: function() {
                        $('#packagesCurrentPage').val(0);
                        $('#sec').unblock();
                    },
                    success : function(data) {
                        $('#sec').html(dataFilter(data));
                        $('#packagesCurrentPage').val(0);
                        //with this we copy the latest cache from pagination in the panel (the panel is not being reloaded when paginating and we need this prevcachekey updated for facet previous state)
                        $('#prevCacheKeyId').val( $('#prevCacheKeyPagination').val())
                        $('#sec').unblock();
                        element_to_scroll_to = document.getElementById('WarningAnchor');
                        element_to_scroll_to.scrollIntoView();
                        multiModalCall();
                        if (typeof dataLayer != 'undefined'){
                			dataLayer.push({'event': 'dataLoaded'});
                		}
                    }
                });
            } else {
                $.ajax ({
                    type : "POST",
                    url : "/ota/" + $('#tabName').val() + "asyncsearchresult",
                    data : $('#searchPanelFormId').find('input, select').not('[value=""], [value="-1"],[value="on"]').serialize(),
                    error: function() {
                        $('#packagesCurrentPage').val(0);
                        $('#sec').unblock();
                    },
                    success : function(data) {
                        $('#sec').html(dataFilter(data));
                        $('#packagesCurrentPage').val(0);
                        //with this we copy the latest cache from pagination in the panel (the panel is not being reloaded when paginating and we need this prevcachekey updated for facet previous state)
                        $('#prevCacheKeyId').val( $('#prevCacheKeyPagination').val())
                        $('#sec').unblock();
                        element_to_scroll_to = document.getElementById('WarningAnchor');
                        element_to_scroll_to.scrollIntoView();
                        multiModalCall();
                        if (typeof dataLayer != 'undefined'){
                			dataLayer.push({'event': 'dataLoaded'});
                		}
                    }
                });
            }
            
        }


        var sortInComparePackages=function(orderType){

            var url = "/ota/sortComparePage?";
            url=url+"&orderType="+orderType;

            $('#'+"ter").block({ message: waitingMessage, css: {  } });
            $('#'+"ter").load(url,{},function(){
                $('#'+"ter").unblock();
            });
        }

        var showTabView=function(packagesCurrentPage,displayType) {
            $('#displayType').val(displayType);

            if (displayType=='detailedView' && !$('#goToDetailedView').hasClass('active')) {
                $('#goToDetailedView').addClass('active');
                $('#goToDetailedViewB').addClass('active');
                $('#goToImageView').removeClass();
                $('#goToImageViewB').removeClass();
                $('#goToMapView').removeClass();
                $('#goToMapViewB').removeClass();
                if (!($('#detailedViewLoaded').length > 0)) {
                    loadViewContent(packagesCurrentPage,'detailedView');
                } else {
                    $("#detailedViewContent").css("display", "block");
                    $("#imageViewContent").css("display", "none");
                    $("#mapViewContent").css("display", "none");
                }
            } else if (displayType=='imageView' && !$('#goToImageView').hasClass('active')) {
                $('#goToImageView').addClass('active');
                $('#goToImageViewB').addClass('active');
                $('#goToDetailedView').removeClass();
                $('#goToDetailedViewB').removeClass();
                $('#goToMapView').removeClass();
                $('#goToMapViewB').removeClass();
                if (!($('#imageViewLoaded').length > 0)) {
                    loadViewContent(packagesCurrentPage,'imageView');
                } else {
                    $("#detailedViewContent").css("display", "none");
                    $("#imageViewContent").css("display", "block");
                    $("#mapViewContent").css("display", "none");
                }
            }  else if (displayType=='mapView' && !$('#goToMapView').hasClass('active')) {
                $('#goToMapView').addClass('active');
                $('#goToMapViewB').addClass('active');
                $('#goToDetailedView').removeClass();
                $('#goToDetailedViewB').removeClass();
                $('#goToImageView').removeClass();
                $('#goToImageViewB').removeClass();

                if (!($('#imageMapLoaded').length > 0)) {
					//initMap();
					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.src = 'http://maps.googleapis.com/maps/api/js?v=3.9&sensor=false&language='+contentLanguage+'&callback=SRP.search.initMap';
					document.body.appendChild(script);
					packagesCurrentPageGlobal = packagesCurrentPage;
                    //loadViewContent(packagesCurrentPage,'mapView')
                }  else {
                    $("#detailedViewContent").css("display", "none");
                    $("#imageViewContent").css("display", "none");
                    $("#mapViewContent").css("display", "block");
                }
            }
            element_to_scroll_to = document.getElementById('WarningAnchor');
            element_to_scroll_to.scrollIntoView();
        }
		
		var initMap=function() {
			loadViewContent(packagesCurrentPageGlobal,'mapView');
		}

        var loadViewContent=function(packagesCurrentPage,displayView) {

            // need to hardcode top positioning as height too large
            $('#sec').block({ message: waitingMessage, centerY: 0,	css: { top: '105px'} });

            $('#packagesCurrentPage').val(packagesCurrentPage);

            if(isPapi()) {
                $.ajax ({
                    type : "POST",
                    url : "/ota/" + $('#tabName').val() + "tabs",
                    data : $('#searchPanelFormId').find('input, select').not('[value=""], [value="-1"],[type=checkbox][checked]').serialize(),
                    error: function() {
                        $('#packagesCurrentPage').val(0);
                        $('#sec').unblock();
                    },
                    success : function(data) {
                        $('#'+ displayView + 'Content').html(dataFilter(data));
                        if (displayView=='imageView') {
                            $("#detailedViewContent").css("display", "none");
                            $("#imageViewContent").css("display", "block");
                            $("#mapViewContent").css("display", "none");
                        } else if (displayView=='mapView') {
                            $("#detailedViewContent").css("display", "none");
                            $("#imageViewContent").css("display", "none");
                            $("#mapViewContent").css("display", "block");
                        } else {
                            $("#detailedViewContent").css("display", "block");
                            $("#imageViewContent").css("display", "none");
                            $("#mapViewContent").css("display", "none");
                            multiModalCall();
                        }
                        $('#packagesCurrentPage').val(0);
                        $('#sec').unblock();
                        element_to_scroll_to = document.getElementById('WarningAnchor');
                        element_to_scroll_to.scrollIntoView();
                    }
                });
            }
            else {
                $.ajax ({
                    type : "POST",
                    url : "/ota/" + $('#tabName').val() + "tabs",
                    data : $('#searchPanelFormId').find('input, select').not('[value=""], [value="-1"], [value="on"]').serialize(),
                    error: function() {
                        $('#packagesCurrentPage').val(0);
                        $('#sec').unblock();
                    },
                    success : function(data) {
                        $('#'+ displayView + 'Content').html(dataFilter(data));
                        if (displayView=='imageView') {
                            $("#detailedViewContent").css("display", "none");
                            $("#imageViewContent").css("display", "block");
                            $("#mapViewContent").css("display", "none");
                        } else if (displayView=='mapView') {
                            $("#detailedViewContent").css("display", "none");
                            $("#imageViewContent").css("display", "none");
                            $("#mapViewContent").css("display", "block");
                        } else {
                            $("#detailedViewContent").css("display", "block");
                            $("#imageViewContent").css("display", "none");
                            $("#mapViewContent").css("display", "none");
                        }
                        $('#packagesCurrentPage').val(0);
                        $('#sec').unblock();
                        element_to_scroll_to = document.getElementById('WarningAnchor');
                        element_to_scroll_to.scrollIntoView();
                    }
                });
            }
        }

//:open modal  whats included
        $(function () {
            multiModalCall();
        });

        var multiModalCall=function() {
            "use strict";
            var modalBackdrop = '<div id="modalBackdrop" class="fade in"></div>';
            var modal = '<div class="modal fade in">' +
                '<div class="modal-hd">' +
                '<a data-dismiss="modal" class="close" href="#">&times;</a>' +
                '<h2></h2>' +
                '</div>' +
                '<div class="modal-bd"></div>' +
                '<div class="modal-ft"></div>' +
                '</div>';
            var $modalTrigger = $('[data-toggle=multimodal]');
            $modalTrigger.click(function (e) {
                if($('#whatsIncludedHidden'+$(this).data('id'))!=''){
                    modal=$('#whatsIncludedHidden'+$(this).data('id'));
                    //console.log(modal.html());
                }
                e.preventDefault();
                $('body').append(modalBackdrop);
                $('body').append(modal.css("display","block"));
                // :close modal
                $('[data-dismiss=modal]').click(function (e) {
                    e.preventDefault();
                    $('.modal').css("display","none");
                    $('#modalBackdrop').remove();
                });
            });

        }

        return {addToCompareTray : addToCompareTray,
            changeInputHiddenOrderType:changeInputHiddenOrderType,
            removeFromComparePage:removeFromComparePage,
            displayCompareTray:displayCompareTray,
            isPapi:isPapi,
            sortAndPaginatePackages:sortAndPaginatePackages,
            searchAsyncCall:searchAsyncCall,
            searchCall:searchCall,
            sortInComparePackages:sortInComparePackages,
            showTabView:showTabView,
            loadViewContent:loadViewContent,
			initMap:initMap,
            multiModalCall:multiModalCall
        }

}(SRP||{},jQuery));


